package com.jh.user.pojo.freeQuick;

import cn.jh.common.pay.interfaces.RetCode;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.google.common.base.MoreObjects;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author Fuchun
 * @since 1.0
 */
@JsonPropertyOrder({ "ret_code", "ret_msg", "sign" })
public class OutEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    public static OutEntity success() {
        return new OutEntity(RetCode.SUCCESS);
    }

    public static OutEntity of(RetCode retCode) {
        return new OutEntity(retCode);
    }

    public static OutEntity of(String retCode, String retMsg) {
        return new OutEntity(retCode, retMsg);
    }

    private String retCode;
    private String retMsg;
    private String sign;

    private transient String signContent;

    public OutEntity(RetCode retCode) {
        this(retCode.getCode(), retCode.getMessage());
    }

    public OutEntity(String retCode, String retMsg) {
        this.retCode = retCode;
        this.retMsg = retMsg;
    }

    public String getRetCode() {
        return retCode;
    }

    public void setRetCode(String retCode) {
        this.retCode = retCode;
    }

    public String getRetMsg() {
        return retMsg;
    }

    public void setRetMsg(String retMsg) {
        this.retMsg = retMsg;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    /**
     * 检查请求是否需要成功返回。
     *
     * @return 如果请求需要成功返回，则返回{@code true}，否则{@code false}。
     */
    @JsonIgnore
    public boolean isSussess() {
        return RetCode.SUCCESS.getCode().equals(retCode);
    }

    @JsonIgnore
    public String getSignContent() {
        if (signContent != null) return signContent;
        List<String> parts = new ArrayList<>(10);
        parts.add(getRetCode());
        applySign(parts);
        signContent = String.join("_", parts);
        return signContent;
    }

    protected void applySign(List<String> parts) {

    }

    MoreObjects.ToStringHelper toStringHelper(Map<String, Object> map) {
        MoreObjects.ToStringHelper tsh = MoreObjects.toStringHelper(this)
                .add("retCode", retCode)
                .add("retMsg", retMsg);
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                tsh.add(entry.getKey(), entry.getValue());
            }
        }
        applyToString(tsh);
        tsh.add("sign", sign);
        return tsh;
    }

    protected void applyToString(MoreObjects.ToStringHelper tsh) {

    }

    @Override
    public String toString() {
        return toStringHelper(null).toString();
    }
}
